﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Xml.Serialization;
using TradeMeSDK;

namespace TradeMo
{
    public class IsolatedStorageRepository<T> where T : class
    {
        private readonly string _filename;
        public IsolatedStorageRepository(string filename)
        {
            _filename = filename;
        }

    	private UserDataStore _dataStore;
    	private UserDataStore DataStore
    	{
    		get { return _dataStore ?? (_dataStore = new UserDataStore()); }
    		set { _dataStore = value; }
    	}

        public void Delete()
        {
			DataStore.Delete(_filename);
        }

        public IEnumerable<T> SelectAll()
        {
        	try
        	{
				return DataStore.Restore<IEnumerable<T>>(_filename);
        	}
        	catch
        	{
        		return new List<T>();
        	}
        }

        public T Get()
        {
            try
            {
            	return DataStore.Restore<T>(_filename);
            }
            catch
            {
            	return null;
            }
        }

        public bool Write(IList<T> items)
        {
            try
            {
            	DataStore.Backup(_filename, items);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public bool Write(T item)
        {
            try
            {
            	DataStore.Backup(_filename, item);
                return true;
            }
            catch
            {
                return false;
            }
        }

    }
}
